package mysupertux.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UDPReceiver extends Thread {
	private static Log log = LogFactory.getLog(UDPReceiver.class);
	
	/** Parent. */
	private UDPNetwork udpNetwork;
	/** Port listening on. */
	private int port;
	/** Socket to receive and send packets. */
	DatagramSocket socket;

	/**
	 * Creates a thread listening to the other player of this game.
	 * 
	 * @param udpNetwork
	 *            the UDPNetwork
	 * @param port
	 *            the port listening on
	 */
	public UDPReceiver(UDPNetwork udpNetwork, int port) {
		this.udpNetwork = udpNetwork;
		this.port = port;

		setDaemon(true);

		// run thread
		start();
	}

	public void run() {
		try {
			// listening
			log.debug("Receiver is listening on port " + port + "...");
			socket = new DatagramSocket(port);

			byte[] buf = new byte[socket.getReceiveBufferSize()];
			DatagramPacket p = new DatagramPacket(buf, buf.length);

			while (!isInterrupted()) {
				socket.receive(p);

				// System.out.println("Receiver: " + new String(p.getData()));
				udpNetwork.receivePacket(p);

				buf = new byte[socket.getReceiveBufferSize()];
				p.setData(buf);
			}

			socket.close();
		} catch (SocketException e) {
			System.out.println("Error listening on UDP port " + port + ": "
					+ e.getMessage());
		} catch (IOException e) {
			System.out.println("Error receiving message: " + e.getMessage());
		}
	}

	public void interrupt() {
		super.interrupt();
		socket.close();
	}
}
